package com.zhang.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.backend.dto.PersonDetailDTO;
import com.zhang.backend.dto.RelationInfoDTO;
import com.zhang.backend.entity.CommonDict;
import com.zhang.backend.entity.Event;
import com.zhang.backend.entity.Person;
import com.zhang.backend.entity.Relation;
import com.zhang.backend.mapper.CommonDictMapper;
import com.zhang.backend.mapper.EventMapper;
import com.zhang.backend.mapper.PersonMapper;
import com.zhang.backend.mapper.RelationMapper;
import com.zhang.backend.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, Person> implements PersonService {

    @Autowired
    private EventMapper eventMapper;
    @Autowired
    private RelationMapper relationMapper;
    @Autowired
    private CommonDictMapper commonDictMapper;
    @Autowired
    private PersonMapper personMapper;

    @Override
    public PersonDetailDTO getPersonDetails(Long personId) {
        Person person = this.getById(personId);
        if (person == null) return null;

        // 1. 获取事件列表
        List<Event> events = eventMapper.selectList(new QueryWrapper<Event>().eq("person_id", personId));

        // 2. 获取关系列表
        // 2.1 查出所有与该人员相关的关系记录
        List<Relation> dbRelations = relationMapper.selectList(new QueryWrapper<Relation>().eq("person_id1", personId));

        // 2.2 查出所有关系类型的定义，并转为Map方便查找
        Map<Integer, String> relationTypeMap = commonDictMapper.selectList(new QueryWrapper<CommonDict>().eq("group_id", 1))
                .stream().collect(Collectors.toMap(CommonDict::getItemId, CommonDict::getItemName));

        // 2.3 组装成RelationInfoDTO列表
        List<RelationInfoDTO> relations = dbRelations.stream().map(rel -> {
            Person relatedPerson = personMapper.selectById(rel.getPersonId2());
            String relationName = relationTypeMap.getOrDefault(rel.getRelationTypeId(), "未知关系");
            return new RelationInfoDTO(relationName, relatedPerson);
        }).collect(Collectors.toList());

        // 3. 组装最终的DTO
        PersonDetailDTO dto = new PersonDetailDTO();
        dto.setPersonInfo(person);
        dto.setEvents(events);
        dto.setRelations(relations);

        return dto;
    }
}